package com.tomcat.myapplication.http;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.tomcat.myapplication.config.PublicConfig;
import com.tomcat.myapplication.http.constants.ConstantExceptionString;
import com.tomcat.myapplication.http.constants.ConstantHttpString;
import com.tomcat.myapplication.http.exception.HttpException;
import com.tomcat.myapplication.util.NetworkUtil;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class HttpInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");
    private Context mContext;
    private Request mRequest;
    private String mType;

    public HttpInterceptor(Context context, String type) {
        this.mType = type;
        this.mContext = context;
    }

    /**
     * 拦截器重写方法
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = null;
        HttpCodeData httpCodeData = null;
        HttpStatusData httpStatusData = null;

        try {
            //判断网络是否可用
            if (!NetworkUtil.isNetworkAvailable(mContext)) {
                throw new HttpException(ConstantExceptionString.CONSTANT_EXCEPTION_ONE, "无网络");
            }

            mRequest = chain.request();
            Request.Builder builder = mRequest.newBuilder();
            // builder.addheader("myhead", "myhead");  //添加头信息
            if (mRequest.url().toString().contains("/front/")){
                if (PublicConfig.userInfo != null) {
                    builder.addHeader("token", PublicConfig.userInfo.getToken());
                }
            }
            builder.addHeader("X-Requested-With","XMLHttpRequest");
            mRequest = builder.method(mRequest.method(), mRequest.body()).build();

            //请求信息
            String strRequestInfo = String.format("RequestHeaders:%s url:%s body:%s", mRequest.headers(), mRequest.url(), mRequest.body());
            response = chain.proceed(mRequest);

            //返回信息
            ResponseBody responseBody = response.body();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = UTF8;//编码
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            //数据转换
            String bodyString = buffer.clone().readString(charset);
            String strResponseInfo = String.format("ResponseBody:%s", bodyString);
            Log.e("shuju",strResponseInfo.toString());

            //自动化解析
            Gson gson = new Gson();
            if (bodyString != null) {//数据不为空

                //判断解析对象格式 主要是针对于json格式不统一的情况
                if (ConstantHttpString.Code_Data.equals(mType)) {

                    httpCodeData = gson.fromJson(bodyString, HttpCodeData.class);
                }else if (ConstantHttpString.Code_Weather.equals(mType) || ConstantHttpString.Code_Air.equals(mType)){

                    httpStatusData = gson.fromJson(bodyString,HttpStatusData.class);
                }else{
                    throw new HttpException(ConstantExceptionString.CONSTANT_EXCEPTION_tWO, "未找到对应解析数据:"+bodyString);
                }
            } else {
                throw new HttpException(ConstantExceptionString.CONSTANT_EXCEPTION_tWO, "系统异常请稍后重试");
            }
        } catch (Exception e) {
            throw new HttpException(ConstantExceptionString.CONSTANT_EXCEPTION_tWO, "系统异常请稍后重试:");
        }

        //判断当前请求是哪一个
        switch (mType){
            case ConstantHttpString.Code_Data://登录
                //请求成功
                if ( httpCodeData.isSuccess()) {//请求成功
                    return response;
                } else  { //请求失败
                    //自定义异常
                    throw new HttpException(ConstantExceptionString.CONSTANT_EXCEPTION_THREE, httpCodeData.getMsg());
                }
            case ConstantHttpString.Code_Weather://天气
                if (httpStatusData.getData().get(0) != null ){
                    return response;
                }else {
                    throw new HttpException(ConstantExceptionString.CONSTANT_EXCEPTION_THREE, "获取数据失败");
                }
            case ConstantHttpString.Code_Air://天气
                if (httpStatusData.getData().get(0) != null ){
                    return response;
                }else {
                    throw new HttpException(ConstantExceptionString.CONSTANT_EXCEPTION_THREE, "获取数据失败");
                }
        }
        throw new HttpException(ConstantExceptionString.CONSTANT_EXCEPTION_tWO, "系统异常");
    }
}
